<?php
/**
 * 作用：微信卡券处理模块
 * 作者: shijy@soe-soe.com
 * 日期: 2016/4/27 15:41
 * 公司: 浙江宣逸网络科技有限公司<www.soe-soe.com>
 */
namespace Common\Model;
class WeixinTicketModel extends BaseModel{
	//微信卡券，在微信平台上的状态属性
	const CODE_STATUS_NOT_VERIFY	='CODE_STATUS_NOT_VERIFY';	//待审核
	const CODE_STATUS_VERIFY_FAIL	='CODE_STATUS_VERIFY_FAIL';	//审核失败
	const CODE_STATUS_VERIFY_OK		='CODE_STATUS_VERIFY_OK'; 	//通过审核
	const CODE_STATUS_USER_DELETE	='CODE_STATUS_USER_DELETE'; //卡券被商户删除
	const CODE_STATUS_DISPATCH		='CODE_STATUS_DISPATCH';	//在公众平台投放过的卡券


	//微信卡券审核状态
	const WEIXIN_CHECK_DEFAULT		=0;//新增、修改后的默认状态
	const WEIXIN_CHECK_PASS			=1;//微信端推送过来的状态，审核通过
	const WEIXIN_CHECK_UNPASS		=2;//微信端推送过来的状态，审核不通过



	//卡券号展示类型，针对微信
	const CODE_TYPE_TEXT		= 'CODE_TYPE_TEXT';
	const CODE_TYPE_BARCODE		= 'CODE_TYPE_BARCODE';
	const CODE_TYPE_QRCODE		= 'CODE_TYPE_QRCODE';


	const ONCE_DEPOSIT_CODE_MAX_NUM=100;//单次导入code最多允许个数



	/**
	 * 各类微信卡券基础数据
	 * Author: shijy
	 * @param $brandName
	 * @param $codeType
	 * @param $title
	 * @param $subTitle
	 * @param $color
	 * @param $notice
	 * @param $servicePhone
	 * @param $description
	 * @param $beginTimestamp
	 * @param $endTimestamp
	 * @param $quantity
	 * @param $getLimit
	 * @param $location_id_list
	 * @param $useCustomCode
	 * @param $depositCode
	 * @return array
	 */
	public static function create_card_baseInfo($brandName,$codeType,$title,$subTitle,$color,$notice,$servicePhone,$description,$beginTimestamp,$endTimestamp,$quantity,$getLimit,$location_id_list,$useCustomCode,$depositCode){
		$baseInfo= array(
			"logo_url"=>WX_CARD_LOGO_URL,
           "brand_name"=>urlencode($brandName),
           "code_type"=>$codeType,
           "title"=>urlencode($title),
           "sub_title"=>urlencode($subTitle),
           "color"=>$color,
           "notice"=>urlencode($notice),
           "service_phone"=>$servicePhone,
           "description"=>urlencode($description),
           "date_info"=>array(
			   "type"=>"DATE_TYPE_FIX_TIME_RANGE",
               "begin_timestamp"=>$beginTimestamp ,
               "end_timestamp"=>$endTimestamp
			),
           "sku"=>array(
				"quantity"=>$quantity
			),
           "get_limit"=>$getLimit,
           "bind_openid"=> true,
           "can_share"=> false,
           "can_give_friend"=> false,
           "custom_url_name"=> "",
           "custom_url"=> "",
           "custom_url_sub_title"=> "",
           "promotion_url_name"=> "",
           "promotion_url"=> "",
           "source"=> ""
		);
		if(is_array($location_id_list)){
			$baseInfo["location_id_list"] =array();
			foreach($location_id_list as $one) {
				$baseInfo["location_id_list"][] = $one;
			}
		}else{
			$baseInfo['use_all_locations']=true;
		}
		if($useCustomCode){
			$baseInfo['use_custom_code']=true;
			if($depositCode){
				$baseInfo['get_custom_code_mode']='GET_CUSTOM_CODE_MODE_DEPOSIT';
			}
		}else{
			$baseInfo['use_custom_code']=false;
		}
		return $baseInfo;
	}


	public static function getCode($weixinCardId,$code){
		$url='https://api.weixin.qq.com/card/code/get?access_token=';
		$data=array(
			'card_id'=>$weixinCardId,
			'code'=>$code,
			'check_consume'=>true
		);

		$content=urldecode(json_encode($data));
		return WeixinModel::send($url,$content);
	}

	/**
	 * 创建微信卡券_团购
	 * url:http://mp.weixin.qq.com/wiki/8/b7e310e7943f7763450eced91fa793b0.html#.E5.9B.A2.E8.B4.AD.E5.88.B8
	 * Author: shijy
	 * @param $deal_detail
	 * @return array|mixed
	 */
	public static function create_card_groupon($deal_detail,$baseInfo){
		$url='https://api.weixin.qq.com/card/create?access_token=';
		$cardType='GROUPON';
		$lowerCardType=strtolower($cardType);
		$upperCardType=strtoupper($cardType);
		$data=array(
			'card'=>array(
				'card_type'=>$upperCardType,
				$lowerCardType=>array(
					'base_info'=>$baseInfo,
					'deal_detail'=>urlencode($deal_detail)
				)
			)
		);

		$content=urldecode(json_encode($data));
		return WeixinModel::send($url,$content);
	}
	/**
	 * 查看指定卡券详情
	 * url:http://mp.weixin.qq.com/wiki/3/3f88e06725fd911e6a46e2f5552d80a7.html
	 * Author: shijy
	 * @param $card_id 微信卡券编号
	 * @return mixed
	 */
	public static function get_card_info($card_id){
		$url="https://api.weixin.qq.com/card/get?access_token=";
		$content='{"card_id":"'.$card_id.'"}';
		return WeixinModel::send($url,$content);
	}

	public static function get_card_stock($weixin_card_id){
		$result=self::get_card_info($weixin_card_id);
		return $result['data']['card']['groupon']['base_info']['sku']['quantity'];
	}

	/**
	 * 批量获取卡券信息
	 * url:http://mp.weixin.qq.com/wiki/3/3f88e06725fd911e6a46e2f5552d80a7.html#.E6.9F.A5.E7.9C.8B.E5.8D.A1.E5.88.B8.E8.AF.A6.E6.83.85
	 * Author: shijy
	 * @param $card_id_list
	 * @return mixed
	 */
	public static function get_card_batch($offset,$count,$card_id_list){
		$url="https://api.weixin.qq.com/card/batchget?access_token=";
		$data=array(
			'offset'=>$offset,
			'count'=>$count,
			'status_list'=>(array)$card_id_list
		);
		$content=json_encode($data);
		return WeixinModel::send($url,$content);
	}


	/**
	 * 删除卡券
	 * Author: shijy
	 * @param $card_id
	 * @return int|mixed
	 * @throws my_exception
	 */
	public static function delete_card($card_id){
		$url="https://api.weixin.qq.com/card/delete?access_token=";
		$content='{"card_id":"'.$card_id.'"}';
		return WeixinModel::send($url,$content);
	}


	/**
	 * 设置测试白名单
	 * Author: shijy
	 * @param $openid
	 * @return array|mixed
	 */
	public static function setTestWhiteList($openid){
		$url="https://api.weixin.qq.com/card/testwhitelist/set?access_token=";
		$data=array(
			'openid'=>(array)$openid
		);
		$content=json_encode($data);

		return WeixinModel::send($url,$content);
	}
	/**
	 * 上传卡券code
	 * url:http://mp.weixin.qq.com/wiki/12/ccd3aa0bddfe5211aace864de00b42e0.html#.E5.AF.BC.E5.85.A5.E8.87.AA.E5.AE.9A.E4.B9.89code
	 * Author: shijy
	 * @param $cardId
	 * @param $codeList
	 * @return array|mixed
	 */
	public static function depositCode($wxCardId,$codeList){
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		$codeCount=count($codeList);
		if($codeCount > self::ONCE_DEPOSIT_CODE_MAX_NUM){
			$dataFailure['msg']='单次导入'.$codeCount.'个code，大于上限'.self::ONCE_DEPOSIT_CODE_MAX_NUM;
			return $dataFailure;
		}
		$url="https://api.weixin.qq.com/card/code/deposit?access_token=";

		$data=array(
			'card_id'=>$wxCardId,
			'code'=>$codeList
		);
		$content=json_encode($data);
		return WeixinModel::send($url,$content);
	}


	/**
	 * 核查导入code
	 {
	"errcode":0,
	"errmsg":"ok"
	"exist_code":["11111","22222","33333"],
	"not_exist_code":["44444","55555"]
	}
	 *
	 * Author: shijy
	 * @param $cardId
	 * @param $codeList
	 * @return array|mixed
	 */
	public static function checkDepositCode($cardId,$codeList){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		$codeCount=count($codeList);
		if($codeCount > self::ONCE_DEPOSIT_CODE_MAX_NUM){
			$dataFailure['msg']='单次核查'.$codeCount.'个code，大于上限'.self::ONCE_DEPOSIT_CODE_MAX_NUM;
			return $dataFailure;
		}


		$url="https://api.weixin.qq.com/card/code/checkcode?access_token=";

		$data=array(
			'card_id'=>$cardId,
			'code'=>$codeList
		);
		$content=json_encode($data);

		return WeixinModel::send($url,$content);
	}


	/**
	 * 修改库存
	 * Author: shijy
	 * @param $cardId 微信商卡号
	 * @param $changeNum 变化数量，大于零表示增加，小于零表示减少
	 * @return array|mixed
	 */
	public static function modifyStock($cardId,$changeNum){

		$url="https://api.weixin.qq.com/card/modifystock?access_token=";

		$data=array(
			'card_id'=>$cardId
		);
		$absVal=abs($changeNum);
		if($changeNum>=0){
			$data['increase_stock_value']	= $absVal;
		}else{
			$data['reduce_stock_value']		= $absVal;
		}
		$content=json_encode($data);
		return WeixinModel::send($url,$content);
	}


	/**
	 * 设置卡券号失效
	 * Author: shijy
	 * @param $card_id
	 * @param $code
	 * @return array|mixed
	 */
	public static function unavailable($card_id,$code){
		$url="https://api.weixin.qq.com/card/code/unavailable?access_token=";
		$data=array(
			'card_id'=>$card_id,
			'code'=>$code
		);
		$content=json_encode($data);
		return WeixinModel::send($url,$content);
	}


	/**
	 * 本系统核销卡券，通知微信端
	 * Author: shijy
	 * @param $weixin_cardId 卡券基础编号
	 * @param $code 卡券序列号
	 * @return array|mixed
	 */
	public static function consume($weixin_cardId,$code){
		$url="https://api.weixin.qq.com/card/code/consume?access_token=";
		$data=array(
			'card_id'=>$weixin_cardId,
			'code'=>$code
		);
		$content=json_encode($data);
		return WeixinModel::send($url,$content);
	}



	/**
	 * 上传微信卡券图片
	 * Author: shijy
	 * @param $local_image
	 * @return mixed
	 * @throws my_exception
	 */
	public static function add_image($local_image){
		$url="https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=";
		$content=array(
			'media' => $local_image
		);
		return WeixinModel::send($url,$content);
	}



	
	
	
	
	
	
	
	
	

	//////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////微信卡券相关事件，需合作方实现后通知/////////////////////////////

	/**
	 * 微信端核销卡券
	 * Author: shijy
	 * @param $userOpenID  	所有者openid
	 * @param $cardID			卡券编号
	 * @param $userCardCode    券号
	 * @param $locationName    门店名称
	 * @param $staffOpenId		核销员
	 */
	public static function weixinConsume($userOpenID,$cardID,$userCardCode,$locationName,$staffOpenId){
		
		
	}


	/**
	 * 卡券审核状态变更通知
	 * Author: shijy
	 * @param $cardId
	 * @param $eventSwitch
	 */
	public static function auditChange($cardId,$eventSwitch){
		switch($eventSwitch){
			case 'card_pass_check':
				break;
			case 'card_not_pass_check':
				break;
		}
	}


	/**
	 * 用户在微信上领取卡券后，通知本处理函数
	 * Author: shijy
	 * @param $receiveUserOpenid
	 * @param $cardId
	 * @param $cardCode
	 * @param $OuterId
	 * @return array
	 */
	public static function receiveCard($receiveUserOpenid,$cardId,$cardCode,$OuterId=0){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		$uid=M('u_user_weixin',null,DB_MAIN_CFG)->where("WX1_openID='{$receiveUserOpenid}' or WX2_openID")->getField('uid');
		$data=array(
			'receiveTimestamp'=>time(),
			'uid'=>$uid
		);
		if(M('card_code',null,DB_MAIN_CFG)->where("code='{$cardCode}' and cardId='{$cardId}'")->save($data)==false){
			$dataFailure['msg']='更新失败';
			return $dataFailure;
		}
		return $dataSuccess;
	}


	/**
	 * 卡券删除事件,与unavailable相对应
	 * Author: shijy
	 * @param $receiveUserOpenid
	 * @param $cardId
	 * @param $cardCode
	 * @return array
	 */
	public static function deleteCard($receiveUserOpenid,$cardId,$cardCode){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		$uid=M('u_user_weixin',null,DB_MAIN_CFG)->where("WX1_openID='{$receiveUserOpenid}' or WX2_openID")->getField('uid');
		$data=array(
			'isDel'=>1,
			'uid'=>$uid
		);
		if(M('card_code',null,DB_MAIN_CFG)->where("code='{$cardCode}' and cardId='{$cardId}'")->save($data)==false){
			$dataFailure['msg']='更新失败';
			return $dataFailure;
		}
		return $dataSuccess;
	}




}